/*
 * @Author: gggg 1263457581@qq.com
 * @Date: 2025-05-20 17:40:34
 * @LastEditors: gggg 1263457581@qq.com
 * @LastEditTime: 2025-06-18 17:25:59
 * @FilePath: /algorithm-and-data-struct/socket/client.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;

const int PORT = 8888;
const std::string SERVER_IP = "127.0.0.1";

int main()
{
    int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket == -1) {
        std::cerr << "创建客户端套接字失败" << std::endl;
        return -1;
    }
    sockaddr_in serverAddress;
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = inet_addr(SERVER_IP.c_str());
    serverAddress.sin_port = htons(PORT);

    if (connect(clientSocket, reinterpret_cast<struct sockaddr*>(&serverAddress), sizeof(serverAddress)) < 0) {
        std::cerr << "连接到服务器失败" << std::endl;
        close(clientSocket);
        return -1;
    }

    std::string message = "Hello, I am client!";

    int byteSend = send(clientSocket, message.c_str(), message.length(), 0);
    if (byteSend < 0){
        cout<<"发送数据失败"<<endl;
    }
    char buffer[1024];
    int bytesread = recv(clientSocket, buffer, sizeof(buffer), 0);
    cout<<"recv from server:"<<buffer<<endl;

}